/*
 * @Author: 张久冬
 * @Date: 2021-12-19 21:27:44
 * @
# Description:
 */
import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { ElLoading } from 'element-plus'
import type { jdrequestConfig, jdrequestInterceptor } from './type'

class jdrequest {
  instance: AxiosInstance
  interceptor?: jdrequestInterceptor
  loading?: any
  showLoading: boolean

  constructor(config: jdrequestConfig) {
    this.instance = axios.create(config)
    this.interceptor = config.interceptor
    // 设置showLoading默认值true
    this.showLoading = config.showLoading ?? false
    // 调用请求拦截器
    this.instance.interceptors.request.use(
      this.interceptor?.requestInterceptor,
      this.interceptor?.requestInterceptorCatch
    )

    // 调用响应拦截器
    this.instance.interceptors.response.use(
      this.interceptor?.responseInterceptor,
      this.interceptor?.responseInterceptorCatch
    )

    // 全局拦截器,所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            text: '加载中...'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        if (this.showLoading) {
          this.loading?.close()
          // setTimeout(() => {
          //   this.loading?.close()
          // }, 300)
        }
        return res
      },
      (err) => {
        if (this.showLoading) {
          this.loading?.close()
          // setTimeout(() => {
          //   this.loading?.close()
          // }, 300)
        }
        return err
      }
    )
  }
  request<T = any>(config: jdrequestConfig<T>): Promise<T> {
    // 如果有reques请求有拦截器，就执行一下
    return new Promise((resove, reject) => {
      if (config.interceptor?.requestInterceptor) {
        config = config.interceptor.requestInterceptor(config)
      }
      if (config.showLoading) {
        this.showLoading = config.showLoading ?? false
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptor?.responseInterceptor) {
            res = config.interceptor.responseInterceptor(res)
          }
          // 每次请求都重置loading
          this.showLoading = false
          // 返回请求结果
          resove(res)
        })
        .catch((err) => {
          // 每次请求都重置loading
          this.showLoading = false
          reject(err)
          return err
        })
    })
  }
  get<T = any>(config: jdrequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T = any>(config: jdrequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
}
export default jdrequest
